
import { Pagination, Card } from 'antd';
import { IGetInitialProps, Link, isBrowser } from 'umi'
import InfiniteScroll from 'react-infinite-scroller';
import { useEffect, useRef, useState } from 'react';
import { mockData } from '@/utils/mock'
import styles from './infiniteScroller.less'
import { debounce, throttle } from 'lodash';



const mockFetch = async (page,) => {
  return mockData(page, 25,)
}

type Props = {
  currentPage: number;
  path: string;
  preFetchData: any;
}
const Index: React.FC<Props> & { getInitialProps: IGetInitialProps<Props, { page: any }> } = (props) => {
  const [width, setWidth] = useState<number>()
  const itemWidth = useRef(275);
  const marginRight = useRef(24)
  const caclcWidth = () => {
    const num = Math.floor((window.innerWidth - marginRight.current) / (itemWidth.current + marginRight.current))
    setWidth(num * itemWidth.current + (num - 1) * marginRight.current)
    console.log(num)
  }
  const resize = useRef(debounce(() => caclcWidth(), 500)).current

  useEffect(() => {
    caclcWidth();
    window.addEventListener('resize', resize,)
  }, [])
  const loadFunc = (e) => {
    console.log(e)
  }
  // 服务端预请求数据接管到state
  const [data, setData] = useState<any[]>(props.preFetchData || [])
  return (
    <div className={styles.a}>
      <div className={styles.main} style={{ width: `${width}px` }}>
        <div className={styles.title}>
          title
        </div>
        <InfiniteScroll
          // initialLoad={false}
          pageStart={0}
          loadMore={loadFunc}
          hasMore={true || false}
          loader={<div className="loader" key={0}>Loading ...</div>}
        >

          <div className={styles.scrollmain}>
            {data.map(item => {
              return <div key={item.id} className={styles.item}>
                <div className={styles.content}>{item.title}</div>
              </div>
            })}
          </div>
        </InfiniteScroll>
      </div>
    </div>
  );
};


// 服务端预渲染
Index.getInitialProps = (async ({ match, }) => {
  const { path, params } = match;
  const { page, } = params;
  console.log(match)
  const response = await mockFetch(page);
  return {
    path,
    currentPage: page,
    preFetchData: response,
  };
})






export default Index;
